<template>
  <div class="wrapper">
    <!-- 头部 -->
    <div>
      <div class="user-info">
        <a class="user-link" @click="personalPage">
          <i class="fa fa-user"></i> {{ user.name }}
        </a>
      </div>
    </div>


    <div class="main-content">
      <h2 class="content-title">用户信息</h2>
      <div class="table-actions">
        <button class="btn-primary" @click="handleAdd">新增</button>
        <div class="search-box">
          <div class="input-container">
            <input
                type="text"
                v-model="searchKeyword"
                @keyup.enter="loadData(1)"
                placeholder="请输入搜索内容"
            >
            <i class="fa fa-search"></i>
          </div>
          <el-button type="primary" @click="loadData(1)">搜索</el-button>
        </div>
      </div>

      <!-- 数据表格 -->
      <table class="data-table">
        <thead>
        <tr>
          <th v-for="column in columns" :key="column">{{ column }}</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="item in tableData" :key="item.id">
          <td>{{ item.name }}</td>
          <td>{{ item.nickName }}</td>
          <td>{{ item.sex }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.phone }}</td>
          <td>{{ item.email }}</td>
          <td>
            <button class="btn-edit" @click="handleEdit(item)">编辑</button>
            <button class="btn-delete" @click="handleDelete(item.id)">删除</button>
          </td>
        </tr>
        </tbody>
      </table>

      <!-- 分页 -->
      <div class="pagination">
        <button
            :disabled="currentPage === 1"
            @click="loadData(currentPage - 1)"
        >
          上一页
        </button>
        <span class="page-info">第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
        <button
            :disabled="currentPage >= totalPages"
            @click="loadData(currentPage + 1)"
        >
          下一页
        </button>
      </div>
    </div>

    <!-- 编辑模态框 -->
    <div v-if="showModal" class="modal-mask">
      <div class="modal-wrapper">
        <div class="modal-container">
          <div class="modal-header">
            <h3>{{ formData.id ? '编辑用户' : '新增用户' }}</h3>
            <i class="fa fa-times close-icon" @click="closeModal"></i>
          </div>
          <div class="modal-body">
            <form @submit.prevent="handleSubmit">
              <div class="form-group">
                <label>姓名</label>
                <input v-model="formData.name" required>
              </div>
              <div class="form-group">
                <label>昵称</label>
                <input v-model="formData.nickName">
              </div>
              <div class="form-group">
                <label>性别</label>
                <div class="radio-group">
                  <label>
                    <input
                        type="radio"
                        v-model="formData.sex"
                        value="男"
                        required
                    > 男
                  </label>
                  <label>
                    <input
                        type="radio"
                        v-model="formData.sex"
                        value="女"
                    > 女
                  </label>
                </div>
              </div>
              <div class="form-group">
                <label>年龄</label>
                <input v-model="formData.age" type="number">
              </div>
              <div class="form-group">
                <label>手机号</label>
                <input v-model="formData.phone" pattern="^1\d{10}$">
              </div>
              <div class="form-group">
                <label>邮箱</label>
                <input v-model="formData.email" type="email">
              </div>
              <div class="form-actions">
                <button type="button" @click="closeModal">取消</button>
                <button type="submit">保存</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import request from "@/utils/request.js";


const user = reactive(JSON.parse(localStorage.getItem('user') || '{}'))
const searchKeyword = ref('')
const tableData = ref([])
const currentPage = ref(1)
const totalPages = ref(0)
const showModal = ref(false)
const formData = reactive({
  id: null,
  name: '',
  nickName: '',
  sex: '男',
  age: '',
  phone: '',
  email: ''
})

const columns = ['姓名', '昵称', '性别', '年龄', '手机号', '邮箱', '操作']
const permissions = ref([])

// 生命周期钩子
onMounted(async () => {
  await loadData()
  await fetchPermissions()
})

// 方法
const loadData = async (page = 1) => {
  try {
    const response = await request.get(`/userInfo/page/${searchKeyword.value || 'all'}`, {
      params: {pageNum: page}
    })

    const data = response.data.data
    tableData.value = data.list
    currentPage.value = data.pageNum
    totalPages.value = data.pages
  } catch (error) {
    showError('加载数据失败', error)
  }
}

const handleAdd = () => {
  if (!checkPermission(1)) return
  Object.assign(formData, {
    id: null,
    name: '',
    nickName: '',
    sex: '男',
    age: '',
    phone: '',
    email: ''
  })
  showModal.value = true
}

const handleEdit = (item) => {
  if (!checkPermission(3)) return
  Object.assign(formData, item)
  showModal.value = true
}

const handleDelete = async (id) => {
  if (!checkPermission(2)) return

  try {
    await ElMessageBox.confirm('确认删除该用户？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await request.delete(`/userInfo/${id}`)
    ElMessage.success('删除成功')
    await loadData(currentPage.value)
  } catch (error) {
    if (error !== 'cancel') {
      showError('删除失败', error)
    }
  }
}

const handleSubmit = async () => {
  try {
    //const url = formData.id ? '/userInfo' : '/userInfo'
    const url = '/userInfo'
    const method = formData.id ? 'put' : 'post'

    await request[method](url, formData)
    ElMessage.success(formData.id ? '更新成功' : '新增成功')
    closeModal()
    await loadData(formData.id ? currentPage.value : 1)
  } catch (error) {
    showError('操作失败', error)
  }
}

const closeModal = () => {
  showModal.value = false
}

const fetchPermissions = async () => {
  try {
    const response = await request.get('/permission/2')
    permissions.value = response.data.data
  } catch (error) {
    showError('获取权限失败', error)
  }
}

const checkPermission = (code) => {
  if (!permissions.value.includes(code)) {
    ElMessage.warning('无操作权限')
    return false
  }
  return true
}

const personalPage = () => {
  // 个人页面跳转逻辑
}

const showError = (msg, error) => {
  console.error(error)
  ElMessage.error(error.response?.data?.msg || msg)
}
</script>

<style scoped>
.wrapper {
  font-family: Arial, sans-serif;
  margin: 20px;
}


.user-link, .logout-link {
  color: white;
  cursor: pointer;
  text-decoration: none;
}

.table-actions {
  margin: 20px 0;
  display: flex;
  gap: 15px;
  align-items: center;
}

.search-box {
  display: flex;
  align-items: center;
  max-width: 300px;
  gap: 50px; /* 控制输入框和按钮间距 */
}

.search-box input {
  width: 100%;
  padding: 8px 30px 8px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.fa-search {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #666;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  margin: 20px 0;
}

.data-table th, .data-table td {
  border: 1px solid #ddd;
  padding: 12px;
  text-align: left;
}

.data-table th {
  background-color: #f5f5f5;
}

.btn-primary, .btn-edit, .btn-delete {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-edit {
  background-color: #28a745;
  color: white;
  margin-right: 5px;
}

.btn-delete {
  background-color: #dc3545;
  color: white;
}

.pagination {
  margin-top: 20px;
  display: flex;
  align-items: center;
  gap: 15px;
}

.modal-mask {
  position: fixed;
  z-index: 9998;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-container {
  background: white;
  padding: 20px;
  border-radius: 8px;
  width: 500px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.close-icon {
  cursor: pointer;
  font-size: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
}

.form-group input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.radio-group {
  display: flex;
  gap: 15px;
}

.form-actions {
  margin-top: 20px;
  text-align: right;
}
.input-container input {
  padding-right: 30px; /* 给图标留出空间 */
  height: 32px; /* 与按钮高度保持一致 */
}
</style>